package com.sp.reflection.homework;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


/**
 * 练习1:
 * 1. 定义PrivateTest类, 有私有name属性, 并且属性值为helloKitty
 * 2. 提供getName() 的公有方法
 * 3. 创建PrivateTest的类, 提供Class类得到私有的name属性, 提供私有的name属性值,
 *    并调用getName()方法打印name的属性值
 */
public class Homework01 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException {
        //得到PrivateTest类对应的Class对象
        Class<?> aClass = Class.forName("com.sp.reflection.homework.PrivateTest");
        //创建PrivateTest的实例
        Object o = aClass.newInstance();
        Method getName = aClass.getDeclaredMethod("getName");
        System.out.println(getName.invoke(o));

        Field name = aClass.getDeclaredField("name");
        name.setAccessible(true);
        name.set(o, "sp");
        System.out.println(getName.invoke(o));
    }
}


class PrivateTest {
    private String name = "helloKitty";

    public String getName() {
        return name;
    }
}